let express = require('express');
let router = express.Router();
let _ = require('underscore');
let utils = require('./utils');
let requireAuth = utils.requireAuth;
let User = require("../model/user");
let Goods = require("../model/goods");

//我的发布
router.post('/myPublish', requireAuth, (req, res) => {
    User.findOne({openId: req.openid}, (err, user) => {
        Goods
            .find({userId: user._id})
            .populate({
                path: 'userId', 
                select: '-openId'
            })
            .sort('createTime')
            .exec(function(err, goodsList){
                if(err){
                    console.log(err);
                }
                res.json({
                    goodsList: goodsList
                }) 
            })
    })
})
//渲染个人信息
router.post('/personalMessage', requireAuth, (req, res) => {
    User.findOne({openId: req.openid}, (err, user) => {
        if(user){
            res.json({
                user: {
                    name: user.name,
                    schoolName: user.schoolName,
                    phoneNumber: user.phoneNumber
                }
            })    
        }
    })
})

//修改个人信息
router.post('/personalMessage/new', requireAuth, (req, res) => {
    // console.log(req.openid);
    let userObj = req.body.user;

    User.findOne({openId: req.openid}, (err, user) => {
        if(user){
            let _user = _.extend(user, userObj);  // _.extend用新对象里的字段替换老的字段  
            _user.save((err, movie) => {
                if(err){
                    console.log(err);
                }
            });
            res.json({
                message: 'personalMessage success!'
            })            
        }
    })
});

module.exports = router;